﻿using System;
using ExpressionEngine;
using DevExpress.XtraReports.UI;
using ExpressionEngine.ValueProviders;

namespace XtraReportsExpressionSummary
{
    public static class ExpressionSummaryExtender
    {
        public static void SetExpression(this XRLabel lable, string expression)
        {
            AggregateExpressionEvaluator expressionEvaluator = new AggregateExpressionEvaluator(expression);

            lable.SummaryReset += (s, e) => expressionEvaluator.Reset();
            lable.SummaryRowChanged += (s, e) =>
            {
                XRControl control = (XRControl)s;
                expressionEvaluator.RowChanged(new ReflectionValueProvider(control.Report.GetCurrentRow()));
            };

            lable.SummaryGetResult += (s, e) =>
            {
                try
                {
                    e.Result = expressionEvaluator.GetResult();
                }
                catch (DivideByZeroException)
                {
                    e.Result = Double.NaN;
                }
                e.Handled = true;
            };
        }
    }
}
